package com.zbl.zblproject.erp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbl.zblproject.core.entity.*;
import com.zbl.zblproject.core.mapper.*;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.core.utils.TimeUtil;
import com.zbl.zblproject.erp.entity.*;
import com.zbl.zblproject.erp.mapper.*;
import com.zbl.zblproject.erp.service.ErpGoodService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/9
 * ErpGood的数据处理层
 */
@Service
@Transactional
public class ErpGoodServiceImpl implements ErpGoodService {


    @Autowired
    private ErpWarehouseMapper erpWarehouseMapper;

    @Autowired
    private ErpTempOrderItemMapper erpTempOrderItemMapper;

    @Autowired
    private ErpGoodMapper erpGoodMapper;

    @Autowired
    private ErpCategoryMapper erpCategoryMapper;

    @Autowired
    private BrandMapper erpBrandMapper;

    @Autowired
    private SupplierMapper erpSupplierMapper;

    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private SmallUnitMapper smallUnitMapper;

    @Autowired
    private ErpOweGoodsItemMapper oweGoodsItemMapper;

    @Autowired
    private ErpOrderItemMapper erpOrderItemMapper;

    @Autowired
    private ErpWarehouseItemMapper warehouseItemMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private PriceMapper priceMapper;

    private static final Logger logger = LoggerFactory.getLogger(ErpGoodService.class);

    @Override
    public boolean deleteErpGood(List<Integer> id) {
        int size = erpGoodMapper.deleteBatchIds(id);
        return id.size() == size;
    }

    @Override
    public boolean deleteErpGoodBySn(String sn) {
        QueryWrapper<ErpGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_sn", sn);
        return erpGoodMapper.delete(wrapper) == 1;
    }

    @Override
    public ErpGoods selectById(int id) {
        ErpGoods good = erpGoodMapper.selectById(id);
        if (good != null) {
            good.setErpBrand(erpBrandMapper.selectById(good.getBrandId()));
            good.setErpCategory(erpCategoryMapper.selectById(good.getCatId()));
            good.setErpSupplier(erpSupplierMapper.selectById(good.getSuppliersId()));
            good.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(good.getGoodsId()));
            SmallUnit smallUnit = smallUnitMapper.selectById(good.getSmallunitId());
            if (smallUnit == null) {
                good.setSmallUnitName("件");
            } else {
                good.setSmallUnitName(smallUnit.getName());
            }
            if (good.getDefaultWarehouse() != null) {
                good.getDefaultWarehouse().setStock(warehouseItemMapper.getGoodsNumberByWhId(good.getGoodsId(), good.getDefaultWarehouse().getId()));
            }
        }

        return good;
    }

    @Override
    public ErpGoods selectByIdPure(int id) {
        ErpGoods good = erpGoodMapper.selectById(id);
        String name = smallUnitMapper.selectUnitNameById(good.getSmallunitId());
        good.setSmallUnitName(name);
        System.out.println(good.toString());
        return good;
    }

    //todo 优化
    @Override
    @Cacheable(value = "app", key = "'orderSn:' +#orderSn ", sync = true)
    public ErpGoods selectBySn(String orderSn) {
        QueryWrapper<ErpGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_sn", orderSn).or().eq("commodity_code", orderSn);

        List<ErpGoods> goods = erpGoodMapper.selectList(wrapper);
        ErpGoods good = null;
        if (goods != null && !goods.isEmpty()) {
            good = goods.get(0);
        } else {
            throw new RuntimeException("没有查询到对应数据");
        }
        if (good != null) {
            good.setErpBrand(erpBrandMapper.selectById(good.getBrandId()));
            good.setErpCategory(erpCategoryMapper.selectById(good.getCatId()));
            good.setErpSupplier(erpSupplierMapper.selectById(good.getSuppliersId()));
            good.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(good.getGoodsId()));
            if (good.getDefaultWarehouse() != null) {
                good.getDefaultWarehouse().setStock(warehouseItemMapper.getGoodsNumberByWhId(good.getGoodsId(), good.getDefaultWarehouse().getId()));
            }
            SmallUnit smallUnit = smallUnitMapper.selectById(good.getSmallunitId());
            if (smallUnit == null) {
                good.setSmallUnitName("件");
            } else {
                good.setSmallUnitName(smallUnit.getName());
            }
            if (good.getVipPrice() == null) {
                good.setVipPrice(BigDecimal.valueOf(0));
            }
        }

        return good;
    }

    private List<Integer> cates(int cate) {
        List<Integer> cates = new ArrayList<>();
        cates.add(cate);
        selectCates(cates, cate);
        return cates;
    }

    private List<Integer> selectCates(final List<Integer> cates, int cate) {
        QueryWrapper<ErpCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", cate);
        List<ErpCategory> list = erpCategoryMapper.selectList(wrapper);
        list.forEach(x -> {
            cates.add(x.getCatId());
            if (x.getParentId() != 0) {
                selectCates(cates, x.getCatId());
            }
        });
        return cates;
    }


    @Override
    public IPage<ErpGoods> erpGoodsList(String search, int current, int size, int cate, int sup, int code, int sale, int status, int brand, String codesn) {
        Page page = new Page(current, size);
        IPage<ErpGoods> erpGoods = null;
        if (cate == -1) {
            erpGoods = erpGoodMapper.selectPageByCateAndSupAndCode(page, StringUtil.sql(search), new ArrayList<>(), sup, code, sale, status, brand, StringUtil.sql(codesn));
        } else {
            erpGoods = erpGoodMapper.selectPageByCateAndSupAndCode(page, StringUtil.sql(search), cates(cate), sup, code, sale, status, brand, StringUtil.sql(codesn));
        }
        erpGoods.getRecords().forEach((x) -> {
            //为Goods置入外置条件
            x.setErpBrand(erpBrandMapper.selectById(x.getBrandId()));
            x.setErpCategory(erpCategoryMapper.selectById(x.getCatId()));
            x.setErpSupplier(erpSupplierMapper.selectById(x.getSuppliersId()));
            x.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(x.getGoodsId()));
            if (x.getDefaultWarehouse() != null) {
                x.getDefaultWarehouse().setStock(warehouseItemMapper.getGoodsNumberByWhId(x.getGoodsId(), x.getDefaultWarehouse().getId()));
            }
            SmallUnit smallUnit = smallUnitMapper.selectById(x.getSmallunitId());
            if (smallUnit == null) {
                x.setSmallUnitName("件");
            } else {
                x.setSmallUnitName(smallUnit.getName());
            }
        });
        return erpGoods;
    }

    @Override
    public IPage<ErpGoods> erpGoodsList(String search, int current, int size, int cate, int sup, int status) {
        Page page = new Page(current, size);
        IPage<ErpGoods> erpGoods = null;
        if (cate == -1) {
            if (sup == -1) {
                erpGoods = erpGoodMapper.selectPageBySearch(page, StringUtil.sql(search), status);
            } else {
                erpGoods = erpGoodMapper.selectPageBySearchAndSup(page, StringUtil.sql(search), sup, status);

            }
        } else {
            if (sup == -1) {
                erpGoods = erpGoodMapper.selectPageByCate(page, StringUtil.sql(search), cates(cate), status);
            } else {
                erpGoods = erpGoodMapper.selectPageByCateAndSup(page, StringUtil.sql(search), cates(cate), sup, status);
            }
        }
        erpGoods.getRecords().forEach((x) -> {
                //带入goods的默认仓库
                //为Goods置入外置条件
                x.setErpBrand(erpBrandMapper.selectById(x.getBrandId()));
                x.setErpCategory(erpCategoryMapper.selectById(x.getCatId()));
            if (erpSupplierMapper.selectById(x.getSuppliersId())!=null) {
                x.setErpSupplier(erpSupplierMapper.selectById(x.getSuppliersId()));
            }else{
                Supplier supplier =new Supplier();
                supplier.setSuppliersName("");
                supplier.setSuppliersDesc("");
                x.setErpSupplier(supplier);
            }
                SmallUnit smallUnit = smallUnitMapper.selectById(x.getSmallunitId());

                if (smallUnit == null) {
                    x.setSmallUnitName("件");
                } else {
                    x.setSmallUnitName(smallUnit.getName());
                }
                x.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(x.getGoodsId()));
                if (x.getDefaultWarehouse() != null) {

                    x.getDefaultWarehouse().setStock(warehouseItemMapper.getGoodsNumberByWhId(x.getGoodsId(), x.getDefaultWarehouse().getId()));
                }
        });
        return erpGoods;
    }

    @Override
    public IPage<ErpGoods> erpGoodsListOfWarehouse(String search, int current, int size) {
        Page page = new Page(current, size);
        IPage<ErpGoods> erpGoods = erpGoodMapper.selectWareItemPage(page, search);

        erpGoods.getRecords().forEach((x) -> {
            //为Goods置入外置条件
            x.setErpBrand(erpBrandMapper.selectById(x.getBrandId()));
            x.setErpCategory(erpCategoryMapper.selectById(x.getCatId()));
            x.setErpSupplier(erpSupplierMapper.selectById(x.getSuppliersId()));
            x.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(x.getGoodsId()));
            if (x.getDefaultWarehouse() != null) {
                x.getDefaultWarehouse().setStock(warehouseItemMapper.getGoodsNumberByWhId(x.getGoodsId(), x.getDefaultWarehouse().getId()));
            }
        });
        return erpGoods;
    }


    @Override
    public ErpGoods erpGoodsOfWarehouseBySn(String goodsSn) {
        ErpGoods goods = erpGoodMapper.selectByGoodsSn(goodsSn);
        if (goods != null) {
            goods.setErpBrand(erpBrandMapper.selectById(goods.getBrandId()));
            goods.setErpCategory(erpCategoryMapper.selectById(goods.getCatId()));
            goods.setErpSupplier(erpSupplierMapper.selectById(goods.getSuppliersId()));
            goods.setDefaultWarehouse(erpWarehouseMapper.selectDefaultWarehouseByGoodsId(goods.getGoodsId()));
            if (goods.getDefaultWarehouse() != null) {
                goods.getDefaultWarehouse().setStock(warehouseItemMapper.getGoodsNumberByWhId(goods.getGoodsId(), goods.getDefaultWarehouse().getId()));
            }
        }
        return goods;
    }

    @Override
    public boolean updateErpGood(ErpGoods good) {
        logger.info("商品产地:{}", good.getPAddress());
        good.setFirstLetter(StringUtil.getFirstSpell(good.getGoodsName()));
        //good.setCommodityCode("");
        int update = erpGoodMapper.updateById(good);

        Brand brand = erpBrandMapper.selectById(good.getBrandId());

        String brandName = "";
        if (brand != null) {
            brandName = brand.getBrandName();
        }
        orderItemMapper.updateOrderItemByUp(good.getShopPrice(),
                brandName, good.getGoodsDesc(), good.getGoodsName(), good.getGoodsId());
        //更新出入库的价格
        List<Integer> toBeUpIds = erpOrderItemMapper.selectToBeUpdatedOrderItem(good.getGoodsId());
        if (!toBeUpIds.isEmpty()) {
            erpOrderItemMapper.updateOrderPriceByIds(good.getShopPrice(), toBeUpIds);

        }
        return update == 1;
    }

    @Override
    public boolean updateByGoodsSn(ErpGoods good) {
        logger.info("商品产地:{}", good.getPAddress());
        good.setFirstLetter(StringUtil.getFirstSpell(good.getGoodsName()));
        good.setCommodityCode("");
        QueryWrapper<ErpGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_sn", good.getGoodsSn());
        int update = erpGoodMapper.update(good, wrapper);

        Brand brand = erpBrandMapper.selectById(good.getBrandId());

        ErpGoods goods = erpGoodMapper.selectByGoodsSns(good.getGoodsSn());

//        String brandName = "";
//        if (brand != null) {
//            brandName = brand.getBrandName();
//        }
        //logger.info("商品存在:{}", goods.getGoodsSn());
//        orderItemMapper.updateOrderItemByUp(good.getShopPrice(),
//                brandName, good.getGoodsDesc(), good.getGoodsName(), goods.getGoodsId());
//        //更新出入库的价格
//        List<Integer> toBeUpIds = erpOrderItemMapper.selectToBeUpdatedOrderItem(goods.getGoodsId());
//        if (!toBeUpIds.isEmpty()) {
//            erpOrderItemMapper.updateOrderPriceByIds(good.getShopPrice(), toBeUpIds);
//        }
        return update == 1;
    }


    @Override
    public boolean addErpGood(ErpGoods erpGood) {
        erpGood.setFirstLetter(StringUtil.getFirstSpell(erpGood.getGoodsName()));
        //todo 添加商品编码 (大分类号) + (中分类号) + （小分类号）
        erpGood.getCatId();
        //erpGood.setCommodityCode("");
        logger.info("商品产地:{}", erpGood.getPAddress());

        String goodsSn = erpGood.getGoodsSn();
        ErpGoods temp = erpGoodMapper.selectByGoodsSns(goodsSn);

        if (temp != null) {
            throw new RuntimeException("商品编号已经重复出现!");
        }
        return 1 == erpGoodMapper.insert(erpGood);
    }


    @Override
    public List<FactoryOrder> listOfStore(String start, String end, String search) {
        LocalDateTime startTime = TimeUtil.parseTime(start);
        LocalDateTime endTime = TimeUtil.parseTime(end);
        long startMillion = startTime.toEpochSecond(ZoneOffset.of("+8"));
        long endMillion = endTime.toEpochSecond(ZoneOffset.of("+8"));
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("financial_confirm", 1).eq("is_cancel", "0").eq("is_pay", 1).ge("create_time", startMillion).le("create_time", endMillion);
        if (!StringUtil.isNullOrEmpty(search)) {
            wrapper.like("order_sn", search);
        }
        //所有待查询的订单号
        List<Order> orders = orderMapper.selectList(wrapper);
        //orders的订单号
        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());

        if (orderSn.isEmpty()) {
            return null;
        }
        //获取所有供应商
        List<Integer> supplierIds = erpSupplierMapper.selectSupplierIdByOrderSn(orderSn);
        //logger.info("工厂订单号数量:{} 工厂订单号:{} 供应商ID:{}", orders.size(), orderSn.toString(), supplierIds);
        List<Supplier> suppliers = erpSupplierMapper.selectBatchIds(supplierIds);
        List<FactoryOrder> factoryOrders = loadSupplier(suppliers, orderSn);
        return factoryOrders;
    }

    @Override
    public List<FactoryOrder> listOfStoreAndConfirm(String start, String end, String search) {
        LocalDateTime startTime = TimeUtil.parseTime(start);
        LocalDateTime endTime = TimeUtil.parseTime(end);
        long startMillion = startTime.toEpochSecond(ZoneOffset.of("+8"));
        long endMillion = endTime.toEpochSecond(ZoneOffset.of("+8"));
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("warehouse_confirm", 1).eq("financial_confirm", 1).eq("is_cancel", "0").eq("is_pay", 1).ge("create_time", startMillion).le("create_time", endMillion);
        if (!StringUtil.isNullOrEmpty(search)) {
            wrapper.like("order_sn", search);
        }
        //所有待查询的订单号
        List<Order> orders = orderMapper.selectList(wrapper);
        //orders的订单号
        List<String> orderSn = orders.stream().map(Order::getOrderSn).collect(Collectors.toList());

        if (orderSn.isEmpty()) {
            return null;
        }
        //获取所有供应商
        List<Integer> supplierIds = erpSupplierMapper.selectSupplierIdByOrderSn(orderSn);
        //logger.info("工厂订单号数量:{} 工厂订单号:{} 供应商ID:{}", orders.size(), orderSn.toString(), supplierIds);
        List<Supplier> suppliers = erpSupplierMapper.selectBatchIds(supplierIds);
        List<FactoryOrder> factoryOrders = loadSupplier(suppliers, orderSn);
        return factoryOrders;
    }

    @Override
    public JSONArray printList(Integer[] ids) {

        JSONArray array = new JSONArray();
        if (ids == null) {
            return array;
        }
        List<ErpGoods> goods = erpGoodMapper.selectBatchIds(Arrays.asList(ids));
        JSONObject object;
        for (ErpGoods good : goods) {
            object = new JSONObject();
            object.put("name", good.getGoodsBrief());
            object.put("sn", good.getGoodsSn());
            SmallUnit unit = smallUnitMapper.selectById(good.getSmallunitId());
            if (unit == null) {
                object.put("unit", "件");
            } else {
                object.put("unit", unit.getName());
            }
            object.put("time", good.getAddTime());
            object.put("desc", good.getGoodsDesc());
            object.put("price", StringUtil.sql(good.getMarketPrice().toString()));
            array.add(object);
        }
        return array;
    }

    @Override
    public List<ErpGoods> stockOutGoods() {
        //前一个月的出货量
        //todo 添加预警周期
        List<Integer> ids = erpGoodMapper.selectStockOutGoods();
        logger.info("预紧库存的商品:{}", ids.toString());
        if (!ids.isEmpty()) {
            List<ErpGoods> goods = erpGoodMapper.selectBatchIds(ids);
            goods.forEach(x -> {
                x.setErpCategory(erpCategoryMapper.selectById(x.getCatId()));
                x.setErpBrand(erpBrandMapper.selectById(x.getBrandId()));
                x.setErpSupplier(erpSupplierMapper.selectById(x.getSuppliersId()));
            });
            return goods;
        }
        return null;
    }

    /**
     * Factory为工厂 工厂订单中为门店 不保存所有项
     *
     * @param suppliers
     * @param orderSn
     * @return
     */
    private List<FactoryOrder> loadSupplier(List<Supplier> suppliers, List<String> orderSn) {
        List<FactoryOrder> list = new ArrayList<>(suppliers.size());
        FactoryOrder factory;

        //String为门店
        List<FactoryItem> userItem;
        for (Supplier supplier : suppliers) {
            factory = new FactoryOrder();
            factory.setSupplier(supplier);
            userItem = new ArrayList<>();

            //查询门店
            List<ErpTempOrderItem> items = erpTempOrderItemMapper.listBySupIdAndOrderSnNotPur(orderSn, supplier.getSuppliersId());
            if (items.isEmpty()) {
                continue;
            }

            for (ErpTempOrderItem item : items) {

                //门店
                AdminUser adminUser = adminUserMapper.selectById(item.getUserId());
                FactoryItem orderItems;
                //将所有数据插入到门店项中

                if (userItem.contains(new SnFactoryItem(item.getOrderSn()))) {
                    orderItems = userItem.get(userItem.indexOf(new SnFactoryItem(item.getOrderSn())));
                    orderItems.getItems().add(item.cloneNew());
                } else {
                    orderItems = new SnFactoryItem();
                    orderItems.setName(adminUser.getUserName());
                    orderItems.setItems(new ArrayList<>());
                    orderItems.getItems().add(item.cloneNew());
                    orderItems.setOrderSn(item.getOrderSn());
                    orderItems.setContext(orderMapper.selectOrderContext(item.getOrderSn()));
                    userItem.add(orderItems);
                }
            }
            factory.setUserItem(userItem);
            list.add(factory);
        }
        return list;
    }


    @Override
    public boolean replenishGoods(int id, int num) {
        ErpOweGoodsItem goodsItem = oweGoodsItemMapper.selectById(id);
        if (goodsItem == null) {
            throw new RuntimeException("没有发现对应的欠缺货信息.");
        }
        if (num > goodsItem.getNumber()) {
            throw new RuntimeException("补出货大于补出货数量.");
        }
        goodsItem.setNumber(goodsItem.getNumber() - num);
        if (goodsItem.getNumber() < 0) {
            throw new RuntimeException("数量异常.");
        }

        //补货仓库添加货物,还货仓库减货物 0:欠货 1:缺货
        return oweGoodsItemMapper.updateById(goodsItem) == 1;

    }

    @Override
    public IPage<ErpGoods> boughtPage(int catId, int brandId, int supplierId, int current, int size, int type, int mode, String name) {
        IPage<ErpGoods> page = new Page<>(current, size);
        if (mode == 0) {
            QueryWrapper<ErpGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 0);
            if (catId != -1) {
                wrapper.eq("cat_id", catId);
            }
            if (brandId != -1) {
                wrapper.eq("brand_id", brandId);
            }
            if (supplierId != -1) {
                wrapper.eq("suppliers_id", supplierId);
            }
            if (!StringUtil.isNullOrEmpty(name)) {
                wrapper.like("goods_name", name)
                        .or()
                        .like("goods_sn", name)
                        .or()
                        .like("first_letter", name)
                ;
            }
            if (type != 0) {
                wrapper.orderByAsc("shop_price");
            }
            page = erpGoodMapper.selectPage(page, wrapper);
        } else {
            page = erpGoodMapper.selectPageForOut(page, catId, brandId, supplierId, name, type);
        }

        page.getRecords().forEach(x -> {
            x.setErpBrand(erpBrandMapper.selectById(x.getBrandId()));
            x.setErpSupplier(erpSupplierMapper.selectById(x.getSuppliersId()));
            x.setErpCategory(erpCategoryMapper.selectById(x.getCatId()));
            //建议采购数量
            x.setRecommendPurchase(Optional.ofNullable(erpGoodMapper.selectAmontOfThisMonth(x.getGoodsId(), x.getOrderCycle())).orElse(0));
            //总销量
            x.setSalesAmount(Optional.ofNullable(erpGoodMapper.selectAmontOfAll(x.getGoodsId())).orElse(0));
        });
        return page;
    }

    @Override
    public List<ErpGoods> getErpGoodsByPreAndFlush(Integer preStatus) {
        QueryWrapper<ErpGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("pre_status", preStatus);
        List<ErpGoods> erpGoods = erpGoodMapper.selectList(wrapper);
        erpGoodMapper.updatePreStatusToZero(preStatus);
        return erpGoods;
    }

    @Override
    public JSONArray selectPrice(String priceSn) {
        JSONArray jsonArray = new JSONArray();
        List<ErpPrice> erpPrices = null;
        if ("-1".equals(priceSn)||StringUtil.isNullOrEmpty(priceSn)){
            erpPrices = priceMapper.selectPriceAll();
            for (ErpPrice erpPrice:erpPrices){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("createTime",erpPrice.getCreate_time());
                jsonObject.put("operator",erpPrice.getOperator());
                jsonObject.put("priceSn",erpPrice.getPrice_sn());
                List<ErpHistoryGoodsPrice> erpHistoryGoodsPrices = priceMapper.selectByPriceId(erpPrice.getPrice_id());
                for (int i=0;i<erpHistoryGoodsPrices.size();i ++){
                    BigDecimal b =new BigDecimal(0);
                    if (erpHistoryGoodsPrices.get(i).getNewMarketPrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewMarketPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getNewPromotePrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewPromotePrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getNewShopPrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewShopPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getNewVipPrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewVipPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldMarketPrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldMarketPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldPromotePrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldPromotePrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldShopPrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldShopPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldVipPrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldVipPrice(b);
                    }
                }
                jsonObject.put("list",erpHistoryGoodsPrices);
                jsonArray.add(jsonObject);
            }
        }else{
            erpPrices = priceMapper.selectPriceByPriceSn(priceSn);
            for (ErpPrice erpPrice:erpPrices){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("createTime",erpPrice.getCreate_time());
                jsonObject.put("operator",erpPrice.getOperator());
                jsonObject.put("priceSn",erpPrice.getPrice_sn());
                List<ErpHistoryGoodsPrice> erpHistoryGoodsPrices = priceMapper.selectByPriceId(erpPrice.getPrice_id());
                for (int i=0;i<erpHistoryGoodsPrices.size();i ++){
                    BigDecimal b =new BigDecimal(0);
                    if (erpHistoryGoodsPrices.get(i).getNewMarketPrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewMarketPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getNewPromotePrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewPromotePrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getNewShopPrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewShopPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getNewVipPrice()==null){
                        erpHistoryGoodsPrices.get(i).setNewVipPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldMarketPrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldMarketPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldPromotePrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldPromotePrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldShopPrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldShopPrice(b);
                    }
                    if (erpHistoryGoodsPrices.get(i).getOldVipPrice()==null){
                        erpHistoryGoodsPrices.get(i).setOldVipPrice(b);
                    }
                }
                jsonObject.put("list",erpHistoryGoodsPrices);
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }
}
